package com.tom.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tom.usercenter.common.ResultCodeEnum;
import com.tom.usercenter.exception.BusinessException;
import com.tom.usercenter.mapper.UserMapper;
import com.tom.usercenter.model.domain.User;
import com.tom.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2024-07-04 20:16:27
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Resource
    private UserMapper userMapper;


    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "yupi";

    String USER_LOGIN_STATE = "userLoginState";

    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @param planetCode    星球编号
     * @return 新用户 id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR, "参数不能为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR, "账户长度不能小于4");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR, "密码长度不能小于8");
        }
        if (planetCode.length() > 5) {
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR, "星球编号不能大于5");
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR, "账户不能包含特殊字符");
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR, "密码和校验密码不相同");
        }
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ResultCodeEnum.USERNAME_USED, "账户已存在");
        }
        // 星球编号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode", planetCode);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR, "星球编号不能重复");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ResultCodeEnum.SYSTEM_ERROR, "用户注册失败");
        }
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
       //校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR, "参数不能为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR, "账户长度不能小于4");
        }
        if (userPassword.length() < 8 ) {
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR, "密码长度不能小于8");
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR, "账户不能包含特殊字符");
        }

        //密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //根据用户名和密码查询用户
       QueryWrapper<User> queryWrapper = new QueryWrapper<>();
       queryWrapper.eq("userAccount", userAccount);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ResultCodeEnum.USERNAME_ERROR, "账户不存在");
        }
       queryWrapper.eq("userPassword", encryptPassword);
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1 == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ResultCodeEnum.PASSWORD_ERROR, "密码错误");
        }

        //对上述获取到的用户信息进行脱敏，然后才能返回给前端
        User FilterUser = getFilterUser(user);
        

        // 登录成功，设置 session
        request.getSession().setAttribute(USER_LOGIN_STATE, FilterUser);
        return FilterUser;

    }

    //把脱敏代码封装成一个通用的方法
    @Override
    public User getFilterUser(User loginUser) {
        if (loginUser== null) {
            return null;
        }
        // 对上述获取到的用户信息进行脱敏，然后才能返回给前端
        User FilterUser = new User();
        FilterUser.setId(loginUser.getId());
        FilterUser.setUserName(loginUser.getUserName());
        FilterUser.setUserAccount(loginUser.getUserAccount());
        FilterUser.setAvatarUrl(loginUser.getAvatarUrl());
        FilterUser.setUserRole(loginUser.getUserRole());
        FilterUser.setGender(loginUser.getGender());
        FilterUser.setPhone(loginUser.getPhone());
        FilterUser.setEmail(loginUser.getEmail());
        FilterUser.setUserStatus(loginUser.getUserStatus());
        FilterUser.setCreateTime(loginUser.getCreateTime());
        FilterUser.setPlanetCode(loginUser.getPlanetCode());
        return FilterUser;

    }

    @Override
    public List<User> queryUser(String username) {
        //校验用户名是否为空
        if(StringUtils.isBlank(username)) {
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR, "用户名不能为空");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("userName", username);
        List<User> userList = userMapper.selectList(queryWrapper);
        //3.返回用户信息
        return userList;

    }

}




